<template>
  <div class="" style="min-height: 500px;" v-loading="loading" element-loading-background="rgba(255, 255, 255 0.8)">
    <div class="flex-row flex-row-reverse" v-if="!saveState.includes('SUCCESS')">
      <el-button type="success" icon="el-icon-download" style="font-size: 14px;padding: 8px;" @click="downloadFile()">下载申请表</el-button>
    </div>
    <div class="aa-container" id="awardform" v-if="!saveState.includes('SUCCESS')">
      <time-line>
        <el-collapse v-model="activeName" accordion>
          <timeline-item :color="activeName === '1' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="项目信息" name="1">
              <template slot="title">项目信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '1'"></i></template>
              <project-info :data.sync="projectinfo" ref="projectinfo"></project-info>
            </el-collapse-item>
          </timeline-item>
          <timeline-item :color="activeName === '2' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="申请单位信息" name="2">
              <template slot="title">申请单位信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '2'"></i></template>
              <app-unit-info :data.sync="appunitinfo" ref="appunitinfo"></app-unit-info>
            </el-collapse-item>
          </timeline-item>
          <timeline-item :color="activeName === '3' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="工程项目介绍" name="3">
              <template slot="title">工程项目介绍&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '3'"></i></template>
              <project-introduce :data.sync="projectintroduce" ref="projectintroduce"></project-introduce>
            </el-collapse-item>
          </timeline-item>
          <timeline-item :color="activeName === '4' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="完成人情况表" name="4">
              <template slot="title">完成人情况表&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '4'"></i></template>
              <com-info :data.sync="cominfo" ref="cominfo"></com-info>
            </el-collapse-item>
          </timeline-item>
          <timeline-item :color="activeName === '5' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="样品及附件清单" name="5">
              <template slot="title">样品及附件清单&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '5'"></i></template>
              <sample-list :data.sync="samplelist" ref="samplelist"></sample-list>
            </el-collapse-item>
          </timeline-item>
          <!-- <timeline-item :color="activeName === '6' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="申报建议及附件信息" name="6">
              <template slot="title">申报建议及附件信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '5'"></i></template>
              <suggest-annex :data.sync="suggestannex" ref="suggestannex"></suggest-annex>
            </el-collapse-item>
          </timeline-item> -->
        </el-collapse>
      </time-line>
      <div class="tc">
        <el-button type="success width-200" plain round @click="goBack()">返回</el-button>
        <el-button type="success width-200" round @click="loading=true,confirm('SAVE')"
        v-if="!row || row && (row.saveSubmit === 'SAVE' || row.verifyStatus === 'FAIL')"
         :loading="loading">{{loading ? '保存中，请稍等' : '保存'}}</el-button>
        <el-button type="success width-200" plain round @click="loading=true,confirm('SUBMIT')"
        v-if="!row || row && (row.saveSubmit === 'SAVE' || row.verifyStatus === 'FAIL')"
         :loading="loading">{{loading ? '提交中，请稍等' : '提交'}}</el-button>
        <el-button type="success width-200" plain round @click="previewResult()">预览</el-button>
      </div>
    </div>

    <div class="va-container flex-column-center promp-msg" v-if="saveState.includes('SUCCESS')">
      <img src="../../assets/shenhetongguo.jpg" alt="" style="margin-top: 100px;">
      <h2 v-show="saveState === 'SAVESUCCESS'">保存成功</h2>
      <h2 v-show="saveState === 'SUBMITSUCCESS'">提交成功</h2>
      <el-button type="success" round @click="corssBack()">
        返回列表
      </el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import eventBus from '../../plugins/eventbus.js'
import AppUnitInfo from './AppUnitInfo'
import ComInfo from './ComInfo'
import ProjectInfo from './ProjectInfo'
import ProjectIntroduce from './ProjectIntroduce'
import SampleList from './SampleList'
// import SuggestAnnex from './SuggestAnnex'

let v = async function (self, isDownload) {
  let result1 = await self.$refs.projectinfo.validate()
  if (!result1) {
    self.activeName = '1'
    return false
  }
  let result2 = await self.$refs.appunitinfo.validate()
  if (!result2) {
    self.activeName = '2'
    return false
  }
  let result3 = await self.$refs.projectintroduce.validate()
  if (!result3) {
    self.activeName = '3'
    return false
  }
  let result4 = await self.$refs.cominfo.validate()
  if (!result4) {
    self.activeName = '4'
    return false
  }

  let result5 = await self.$refs.samplelist.validate()
  if (!result5) {
    let err = self.$refs.samplelist.$validator.errors
    // 下载表单模板时，最后一项的附件不参与验证
    if (err.items.length === 1 && err.has('files12') && isDownload) {
      return true
    }
    self.activeName = '5'
    return false
  }

  // let result6 = await self.$refs.suggestannex.validate()
  // if (!result6) {
  //   self.activeName = '6'
  //   return false
  // }

  return true
}

  export default {

    title: '优秀工程奖申请表单',
    name: 'award-form',
    data () {
      return {
        loading: false,
        saveState: 'WAIT',
        activeName: '1',
        declareType: 'HOLD',
        projectinfo: {
          engineeringAwardId: '', // 工程奖id，后台要求给的，前台不操作
          engineeringName: '',
          isRevise: 'YES',
          applyAward: '',
          resultType: '',
          startTime: '',
          endTime: '',
          totalAmount: ''
        },
        appunitinfo: {
          qualificationCode: '',
          legalRepresentative: '',
          email: '',
          contactAddress: '',
          postalCode: '',
          contacts: '',
          contactsPhone: ''
        },
        projectintroduce: {
          engineeringContent: '',
          technologyInstructions: '',
          instructions: '',
          resultInstructions: ''
        },
        cominfo: [],
        samplelist: [],
        // suggestannex: {
        //   companyPrincipal: '',
        //   companySuggestion: ''
        // },
        row: null,
      }
    },
    methods: {
      confirm (status) {
        v(this).then(result => {
          if (result) {
            // let obj= Object.assign({}, this.row, this.projectinfo, this.appunitinfo, this.projectintroduce, this.suggestannex)
            let obj= Object.assign({}, this.row, this.projectinfo, this.appunitinfo, this.projectintroduce)
            // 完成人组件数据
            obj.mscsEngineeringPeople  = this.cominfo
            // 样品及附件清单数据(将附件中的path中的文件相关转换为字符串)
            obj.mscsEngineeringAttachments = this.samplelist.map((item) => {
              if (item.path.length > 0) {
                if (typeof item.path === 'object') {
                  item.path = JSON.stringify(item.path)
                }
                return item
              } else {
                item.path = ''
                return item
              }
              
            })
            // return
            // obj.userId  = getuser().data.user.userId
            obj.userId = this.$store.state.user.user.user.userId
            obj.saveSubmit = status
            // 其他信息中的附件
            // if (!obj.attachment || obj.attachment.length === 0) { 
            //   obj.attachment = null
            // } else {
            //   if (typeof obj.attachment === 'object') {
            //     obj.attachment = JSON.stringify(obj.attachment)
            //   }
            // }
            this.loading = true
            axios.post('/mscs/award/addEngineeringAwardApply', obj).then((res) => {
              if (res.data.code === 1) {
                this.saveState = status + 'SUCCESS'
                // eventBus.$emit('award-confirm-success')
                // this.$router.go(-1)
              } else {
                this.$codeError(res)
              }
            }).catch((error) => {
              this.$catchError(error)
            }).finally(()=> {
              this.loading = false
            })
          } else {
            this.loading = false
            this.$alert('保存或提交失败，信息填写不完整或不正确，其中标注红色为未填写或填写错误', {
              confirmButtonText: '确定',
            })
          }
        })
      },
      corssBack (flag) {
        eventBus.$emit('award-confirm-success')
        this.$router.go(-1)
        setTimeout(() => {
          this.saveState = 'WAIT'
        }, 100)
      },
      setData (row) {
        this.projectinfo.engineeringAwardId = row.engineeringAwardId // 工程奖id，后台要求给的，前台不操作
        this.projectinfo.engineeringName = row.engineeringName
        this.projectinfo.isRevise = row.isRevise
        this.projectinfo.applyAward = row.applyAward
        this.projectinfo.resultType = row.resultType
        this.projectinfo.startTime = this.$formatYMD(row.startTime)
        this.projectinfo.endTime = this.$formatYMD(row.endTime)
        this.projectinfo.totalAmount = row.totalAmount

        this.appunitinfo.qualificationCode = row.qualificationCode
        this.appunitinfo.legalRepresentative = row.legalRepresentative
        this.appunitinfo.email = row.email
        this.appunitinfo.contactAddress = row.contactAddress
        this.appunitinfo.postalCode = row.postalCode
        this.appunitinfo.contacts = row.contacts
        this.appunitinfo.contactsPhone = row.contactsPhone

        this.projectintroduce.engineeringContent = row.engineeringContent
        this.projectintroduce.technologyInstructions = row.technologyInstructions
        this.projectintroduce.instructions = row.instructions
        this.projectintroduce.resultInstructions = row.resultInstructions

        this.cominfo = row.mscsEngineeringPeople
        this.samplelist.push(...row.mscsEngineeringAttachments)

        // this.suggestannex.companyPrincipal = row.companyPrincipal
        // this.suggestannex.companySuggestion = row.companySuggestion

        this.row = row
      },
      cleartData () {
        this.projectinfo.engineeringAwardId = ''
        this.projectinfo.engineeringName = ''
        this.projectinfo.isRevise = 'YES'
        this.projectinfo.applyAward = ''
        this.projectinfo.resultType = ''
        this.projectinfo.startTime = ''
        this.projectinfo.endTime = ''
        this.projectinfo.totalAmount = ''

        this.appunitinfo.qualificationCode = ''
        this.appunitinfo.legalRepresentative = ''
        this.appunitinfo.email = ''
        this.appunitinfo.contactAddress = ''
        this.appunitinfo.postalCode = ''
        this.appunitinfo.contacts = ''
        this.appunitinfo.contactsPhone = ''

        this.projectintroduce.engineeringContent = ''
        this.projectintroduce.technologyInstructions = ''
        this.projectintroduce.instructions = ''
        this.projectintroduce.resultInstructions = ''

        this.cominfo = []
        this.samplelist = []

        // this.suggestannex.companyPrincipal = ''
        // this.suggestannex.companySuggestion = ''
        this.row = null
      },
      previewResult () {
        // let obj = Object.assign({}, this.projectinfo, this.appunitinfo, this.projectintroduce, this.suggestannex)
        let obj = Object.assign({}, this.projectinfo, this.appunitinfo, this.projectintroduce)
        obj.mscsEngineeringPeople  = JSON.stringify(this.cominfo)
        obj.mscsEngineeringAttachments = JSON.stringify(this.samplelist)
        const {href} = this.$router.resolve({
          name: 'awardpreview',
          query: obj
        })
        window.open(href, '_blank')
      },
      downloadFile () {
        v(this, true).then((result) => {
          if (result) {
            let obj= Object.assign({}, this.row, this.projectinfo, this.appunitinfo, this.projectintroduce)
            // 完成人组件数据
            obj.mscsEngineeringPeople  = this.cominfo
            let params = {
              filePath: 'https://itudou-cloud.pek3b.qingstor.com/document/engineering-award-apply-2.xlsx',
              engineering: JSON.stringify(obj)
            }
            axios.post('/mscs/award/exportEngineeringExcel', this.$paramsConvert(params),{responseType: 'arraybuffer'}).then(res => {
              const content = res.data
              const blob = new Blob([content], {type: "application/vnd.ms-excel"})
              const fileName = '工程将申请表.xlsx'
              if ('download' in document.createElement('a')) { // 非IE下载
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                URL.revokeObjectURL(elink.href) // 释放URL 对象
                document.body.removeChild(elink)
                // let objectUrl = URL.createObjectURL(blob)
                // window.location.href = objectUrl
              } else { // IE10+下载
                navigator.msSaveBlob(blob, fileName)
              }
            }).catch(error => {
              this.$catchError(error)
            })
          } else {
            this.loading = false
            this.$alert('当前无法下载，请填写完整工程奖申请后下载！除‘工程项目奖加盖企业公章的电子扫面件’外，其余信息应全部按照相应格式填写', {
              confirmButtonText: '确定',
            })
          }
        }) 
      },
      goBack () {
        // this.$router.push({name: 'awardapp'})
        this.$router.go(-1)
      }
    },
    beforeRouteEnter (to, from, next) {
     next(vm => {
       let params = to.params
       if (!from.name) {
         params = vm.$lsget('routerToParams')
       }
       // 从错误页面过来，什么都不做
       if (from.name !== 'error-404') {
         if (Object.keys(params).length > 10) {
           vm.setData(params)
         } else {
           vm.cleartData()
         }
       }
     })
    },
    components: {
      'app-unit-info': AppUnitInfo,
      'com-info': ComInfo,
      'project-info': ProjectInfo,
      'project-introduce': ProjectIntroduce,
      'sample-list': SampleList
      // 'suggest-annex': SuggestAnnex
    }
  }
</script>
<style>
  .aa-container {
    padding-top: 25px;
    position: relative;
  }
  .award-prompt {
    margin-top: -20px;
    margin-bottom: 20px;
  }
  /* #awardform {
    padding-top: 50px;
  } */
  #awardform .duigou-con {
    margin-right: 12px;
  }
  #awardform .el-collapse-item__header {
    font-size: 18px;
    color: #3b541c;
    height: auto;
    line-height: normal;
    border-bottom: none;
  }
  /* 去掉展开和默认的底部边框 */
  #awardform .el-collapse {
    border: none;
  }
  #awardform .el-collapse-item__wrap {
    border-bottom: none;
  }
  /* 一下两个是让标识圈偏离整体文档 */
  #awardform .timeline {
    margin-left: -50px;
  }
  #awardform .timeline-item-content {
    padding-left: 50px;
  }
  /* 清除右边展开的标识箭头 */
  #awardform .el-collapse-item__arrow:before {
    content: "";
  }
  /* 让标题文字和右边图标对其 */
  #awardform .el-collapse-item:last-child {
    margin-top: -2px;
  }
  /* 修改展开想的title */
  #awardform .is-active {
    font-size: 20px;
    color: #3b541c;
  }
  #awardform .el-icon-edit:before {
    background: #94C05A;
    border-radius: 50%;
    color: #FFFFFF;
    padding: 3px;
    font-size: 15px;
  }
  /* 暂未查明输入框绿线为什么会差3px */
  /* #awardform .material-textfield label::after {
    bottom: 23px;
  } */
  /* 去掉折叠下方的间距，防止表单出现滚动 */
  #awardform .el-collapse-item__content {
    padding-bottom: 0;
  }
</style>
